package ans.p225;

import java.util.LinkedList;
import java.util.Queue;

/**
 * #      225
 * 名称   用队列实现栈
 * 链接   https://leetcode-cn.com/problems/implement-stack-using-queues
 * 题解   [4512](https://leetcode-cn.com/problems/implement-stack-using-queues/solution)
 * 通过率 67.0%
 * 难道   简单
 */
public class Solution {
    //还有 一种方法每次push的时候 把poll栈的数据弄过来
    class MyStack {
        private Queue<Integer>[] queues = new Queue[2];
        private int mode = 0;

        /**
         * Initialize your data structure here.
         */
        public MyStack() {
            queues[0] = new LinkedList<>();
            queues[1] = new LinkedList<>();
        }

        /**
         * Push element x onto stack.
         */
        public void push(int x) {
            queues[mode].offer(x);
        }

        /**
         * Removes the element on top of the stack and returns that element.
         */
        public int pop() {
            while (queues[mode].size() > 1) {
                queues[(mode + 1) % 2].offer(queues[mode].poll());
            }
            System.out.println(queues[mode].size());
            int res = queues[mode].poll();
            mode = (mode + 1) % 2;
            return res;
        }

        /**
         * Get the top element.
         */
        public int top() {
            int res = 0;
            while (!queues[mode].isEmpty()) {
                Integer poll = queues[mode].poll();
                queues[(mode + 1) % 2].offer(poll);
                if (queues[mode].isEmpty()) {
                    res = poll;
                }
            }
            mode = (mode + 1) % 2;
            return res;
        }

        /**
         * Returns whether the stack is empty.
         */
        public boolean empty() {
            return queues[mode].isEmpty();
        }
    }
}